//
//  MyFirstPageViewController.m
//  Toyohu
//
//  Created by Heige on 16/4/12.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "MyFirstPageViewController.h"
#import "MyTopTableViewCell.h"
#import "TodayKnowTableViewCell.h"
#import "MySearchViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ScrollTableViewCell.h"
#import "PersonalViewController.h"
#import "TodayAndPushTableViewCell.h"
#import "GoodPushTableViewCell.h"
#import "MJRefresh.h"
#import "MySearchViewController.h"
#import "CardViewController.h"
#import "PersonalViewController.h"
#import "GoodPushTwoTableViewCell.h"

#import "MacroDefinition.h"
#import "MyPersonalInfoViewController.h"
#import "masonry.h"
#import "HomeCollectionViewCell.h"
#import "ANTagsView.h"
#import "PeopleInfoViewController.h"

#import "MacroDefinition.h"
#import "GPCustomMD.h"
#import "LocalFileManager.h"
#import "MacroDefinition.h"
#import "NewsDetailViewController.h"

#import "UIView+Fillet.h"

#import "HPViewModel.h"
#import "LoginManager.h"
#import <YYModel.h>
//首页News
#import "HomePageNewsModel.h"
#import "HomeSpaceTableViewCell.h"
#import "HPChildren.h"

#import "HomeTaskModel.h"
#import <AFNetworking.h>

#import "TodayKnowledgeModel.h"
#import "TodayKonwledgeTableViewCell.h"
#import "TYH_LoginLoginModel.h"

static NSString *TodayKonwledgeTableViewCellReuseId = @"TodayKonwledgeTableViewCell";
static NSString *TodayKnowledgeReuseId = @"TodayKnowTableViewCell";
static NSString *MyTopReuseId = @"MyTopTableViewCell";
static NSString *ScrollReuseId = @"ScrollTableViewCell";
static NSString *TodayAndPushReuseId = @"TodayAndPushTableViewCell";
static NSString *GoodPushReuseId = @"GoodPushTableViewCell";
static NSString *GoodPushTwoReuseId = @"GoodPushTwoTableViewCell";
static NSString *HomeSpaceReuseId = @"HomeSpaceTableViewCell";

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height

@interface MyFirstPageViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    
    UIButton *button;
    UILabel *nameLabel;
    UILabel *ageLabel;
    UIButton *searchButton;
    UILabel *mottoLabel;
    UITableView *myTableView;
    UIView *view;
    NSMutableArray *MyTopViewArray;
     NSArray *todayKnowledgeImg;
    double currentPage;
    NSMutableArray *newsArray;
    NSMutableArray *taskArray;
    NSMutableArray *todayKonwledgeArray;
    
    AVAudioPlayer *player;
    UIImageView *voice;
    UIActivityIndicatorView *testActivityIndicator;
    NSCache *cache;
    BOOL shouCache;
    BOOL success;
    BOOL isAnimation;
    NSString *avStr;
    NSMutableArray *idleImages;
}
@property (nonatomic,strong)UITextField *textField;
@property (assign, nonatomic) CGFloat originCellMaxY;

@property (strong, nonatomic)UICollectionView *collectionView;

@property (strong, nonatomic) HPViewModel *hPViewModel;

@end

@implementation MyFirstPageViewController
#pragma mark View LifeCycle
-(void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    [myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    MyTopViewArray = [NSMutableArray array];
    self.originCellMaxY = [self getCellLastControlMaxY];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    
    [self CreateArray];
    
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-49) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
    
    
    UIView *NavView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 30)];
    NavView.backgroundColor = [UIColor whiteColor];
    NavView.layer.cornerRadius = 10;
    NavView.clipsToBounds = YES;
    self.navigationItem.titleView = NavView;
    
    UIImageView *navImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 11, 11)];
    navImg.center = CGPointMake(70, NavView.frame.size.height/2);
    navImg.image = [UIImage imageNamed:@"search_01@2x"];
    [NavView addSubview:navImg];
    
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.text = @"搜索话题和专家";
    tipLabel.font = [UIFont systemFontOfSize:14];
    [tipLabel setTextColor:[UIColor lightGrayColor]];
    [NavView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(navImg.mas_centerY);
        make.width.equalTo(@(140));
        make.height.equalTo(@(20));
        make.left.equalTo(navImg.mas_right).offset(5);
    }];
    
    
    UITapGestureRecognizer *navTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goInToSearchPage)];
    [NavView addGestureRecognizer:navTap];
    
    // 注册单元格
     [myTableView registerNib:[UINib nibWithNibName:@"TodayKnowTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:TodayKnowledgeReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"MyTopTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:MyTopReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"ScrollTableViewCell" bundle:nil] forCellReuseIdentifier:ScrollReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"TodayAndPushTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:TodayAndPushReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"GoodPushTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:GoodPushReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"GoodPushTwoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:GoodPushTwoReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"HomeSpaceTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:HomeSpaceReuseId];
     [myTableView registerNib:[UINib nibWithNibName:@"TodayKonwledgeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:TodayKonwledgeTableViewCellReuseId];
    
    
    myTableView.showsVerticalScrollIndicator = NO;
    myTableView.showsHorizontalScrollIndicator = NO;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    button.selected = NO;

    idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=17; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (unsigned long)i]];
        [idleImages addObject:image];
    }
    
    WS
    myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        SS
        strongSelf.hPViewModel = [[HPViewModel alloc] init];
        
        [strongSelf.hPViewModel getData:^{
            [self getTasks];
            [myTableView reloadData];
            [myTableView.mj_header endRefreshing];
        } error:^(NSString *error) {
//            [SVProgressHUD showErrorWithStatus:error];
            SHOW_NTERROR
            [myTableView.mj_header endRefreshing];
        }];
    }];
    
    myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            SS
            currentPage++;
            [strongSelf getNews];
            
            [myTableView reloadData];
        });
    }];
    MJRefreshGifHeader *rightheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置普通状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [rightheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    myTableView.mj_header = rightheader;
    rightheader.lastUpdatedTimeLabel.hidden = YES;
    rightheader.stateLabel.hidden = YES;
    rightheader.ignoredScrollViewContentInsetTop = - 5;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *rightFooter = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置刷新图片
    [rightFooter setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    myTableView.mj_footer = rightFooter;
    
       
    todayKnowledgeImg = @[@"组-26",@"组-26-拷贝",@"组-26-拷贝-2"];
    [self getTodayKnowledge];
    [self setAudioPlayer];
    [myTableView.mj_header beginRefreshing];
    [myTableView.mj_footer beginRefreshing];
}

-(void)loadNewData
{
    WS
    SS
    strongSelf.hPViewModel = [[HPViewModel alloc] init];
    
    [strongSelf.hPViewModel getData:^{
        [self getTasks];
        [myTableView reloadData];
        [myTableView.mj_header endRefreshing];
    } error:^(NSString *error) {
//        [SVProgressHUD showErrorWithStatus:error];
        SHOW_NTERROR
        [myTableView.mj_header endRefreshing];
        
    }];
    
    
}

-(void)loadMoreData
{
    WS
    SS
    currentPage++;
    [strongSelf getNews];
    
    [myTableView reloadData];
}

#pragma mark 初始化、创建数组
-(void)CreateArray
{
    currentPage = 1;
    if (!newsArray) {
        newsArray = [NSMutableArray array];
    }
    if (!taskArray) {
        taskArray = [NSMutableArray array];
    }
    if (!todayKonwledgeArray) {
        todayKonwledgeArray = [NSMutableArray array];
    }
}

#pragma mark UIScrollViewdelegate
//监听tableView的滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0)
    {
        self.navigationController.navigationBar.hidden = YES;
    }
    else if (scrollView.contentOffset.y>0)
    {
    self.navigationController.navigationBar.hidden = NO;
    }
}
#pragma mark UITableViewdelegate/UItableViewDatasource
//返回UITableView的分组数目
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 7;
}

//返回UITableView每个分组中的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 1;
    }
    else if (section==1){
        return todayKonwledgeArray.count;
    }
    else if (section==2){
        return 1;
    }
    else if (section==3){
        return 1;
    }
    else if (section==4)
    {
        return taskArray.count;
    }
    else if (section==5)
    {
        return 1;
    }
    else if (section==6){
        return newsArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (indexPath.section==0&&indexPath.row==0) {
        myTableView.rowHeight=251;
        MyTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyTopReuseId];
        if (!cell) {
            cell = (MyTopTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: MyTopReuseId];
        }
        [cell.UserImgButton addTarget:self action:@selector(goInToPersonalPage) forControlEvents:UIControlEventTouchDown];
        
        
        [cell setModel:self.hPViewModel.msg.me];
        
        NSArray *tagsToDisplay = [[NSArray alloc] initWithObjects:@"自信",@"勇敢", nil];
        ANTagsView *tagsView = [[ANTagsView alloc] initWithTags:tagsToDisplay frame:CGRectMake(0, -25, 200, 42)];
        [tagsView setTagCornerRadius:7.8];
        [tagsView setBackgroundColor:COLOR(109, 100, 90, 1)];
        [tagsView setTagTextColor:[UIColor whiteColor]];
        [tagsView setBackgroundColor:[UIColor clearColor]];
        [tagsView setFrameWidth:200];
        [cell.tagView addSubview:tagsView];

        
        [cell.SearchButton addTarget:self action:@selector(goInToSearchPage) forControlEvents:UIControlEventTouchDown];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
//        [cell.headImage sd_setImageWithURL:[NSURL URLWithString:_hPViewModel.msg.me.pHeadUrl] placeholderImage:[LocalFileManager getImageForKey:@"myUserImg"]];
        return cell;
    }
    else if(indexPath.section==1&&indexPath.row==0)
    {
        myTableView.rowHeight = 151;
        TodayKonwledgeTableViewCell * cell = [myTableView dequeueReusableCellWithIdentifier:TodayKonwledgeTableViewCellReuseId];
        if (!cell) {
            cell = (TodayKonwledgeTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: TodayKonwledgeTableViewCellReuseId];
            
        }
        cell.myView.layer.borderWidth = 1;
        cell.myView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        cell.myView.layer.cornerRadius = 5;
        cell.myView.clipsToBounds = YES;
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.model = todayKonwledgeArray[indexPath.row];
        return cell;
    }
    else if(indexPath.section==2&&indexPath.row==0){
        myTableView.rowHeight = 150;
        ScrollTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ScrollReuseId];

        if (!cell)
        {
            cell = (ScrollTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: ScrollReuseId];
        }
        
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        cell.title.layer.cornerRadius =10;
        cell.title.clipsToBounds = YES;
        if (_hPViewModel.msg.talk)
        {
            [cell setModelWithTitle:_hPViewModel.msg.talk.tTitle nickName:_hPViewModel.msg.talk.expert.eName headUrl:_hPViewModel.msg.talk.expert.eHeadUrl playerUrl:_hPViewModel.msg.talk.tVoiceUrl];
            if (!shouCache)
            {
                [self performSelectorInBackground:@selector(getPlayerData:) withObject:_hPViewModel.msg.talk.tVoiceUrl];
                shouCache = YES;
                [self setAIV];
            }
        }
        cell.voiceButton.enabled = NO;
        if (avStr) {
            cell.timeLabel.text = avStr;
            cell.voiceButton.enabled = YES;
            
        }
        if (!success) {
            [testActivityIndicator startAnimating];
        }else{
            
        }
        
        if (isAnimation) {
            for (UIImageView*imageView in cell.voiceButton.subviews) {
                [imageView startAnimating];
            }
        }
        UIImageView *imageView = [self getImage];
        imageView.backgroundColor =[UIColor blueColor];
        [cell setImage:imageView];
        testActivityIndicator.center = cell.center;
        [self.view addSubview:testActivityIndicator];
        [testActivityIndicator startAnimating];
        [cell.voiceButton addSubview:testActivityIndicator];
        
        for (UIActivityIndicatorView* activityIndicatorView in cell.voiceButton.subviews) {
            [activityIndicatorView stopAnimating];
        }
        [cell.voiceButton addTarget:self action:@selector(playVoice) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    else if (indexPath.section==3&&indexPath.row==0)
    {
        myTableView.rowHeight=49;
        HomeSpaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeSpaceReuseId];
        if (!cell) {
            cell = (HomeSpaceTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: HomeSpaceReuseId];
        }
        cell.name.text = @"今日任务";
        return cell;
    }
    
    else if (indexPath.section==4)
    {
        myTableView.rowHeight=44;
        TodayAndPushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TodayAndPushReuseId];
        if (!cell) {
            cell = (TodayAndPushTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: TodayAndPushReuseId];
        }
        cell.layer.cornerRadius = 5;
        cell.clipsToBounds = YES;
        cell.backgroundColor = [UIColor colorWithRed:248/255.0 green:186/255.0 blue:146/255.0 alpha:1];
        cell.model = taskArray[indexPath.row];
        HPTask *task = taskArray[indexPath.row];
        if (task.isDone == 1) {
            cell.img.image = [UIImage imageNamed:@"pass"];
        } else {
            cell.img.image = [UIImage imageNamed:@"-not-pass"];
        }
        
        
        if (indexPath.row == 0) {
            cell.topView.hidden = YES;
        } else if(indexPath.row == (taskArray.count - 1)){
            cell.bottomView.hidden = YES;
        }
        if (taskArray.count <= 1) {
            cell.topView.hidden = YES;
            cell.bottomView.hidden = YES;
        }
//        cell.img.image = [UIImage imageNamed:@"-not-pass"];


        if ([GPGET(@"finish")isEqualToString:@"done"]) {
        }
        

        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section==5&&indexPath.row==0)
    {
        myTableView.rowHeight=49;
        HomeSpaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeSpaceReuseId];
        if (!cell) {
            cell = (HomeSpaceTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: HomeSpaceReuseId];
        }
        cell.name.text = @"精彩推荐";
        return cell;
    }
    
    else
    {
        
        if (indexPath.row%2==0)
        {
            myTableView.rowHeight=335;
            GoodPushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GoodPushReuseId];
            if (!cell) {
                cell = (GoodPushTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: GoodPushReuseId];
            }
            
            cell.tagLable.layer.cornerRadius = 10;
            cell.tagLable.clipsToBounds = YES;
            // 针对不同类型的  换不同的颜色
            cell.tagLable.backgroundColor = [UIColor colorWithRed:26/255.0 green:196/255.0 blue:180/255.0 alpha:1];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.model = newsArray[indexPath.row];
            
            return cell;
        }
        
        else
        {
            myTableView.rowHeight=166;
            GoodPushTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GoodPushTwoReuseId];
            if (!cell) {
                cell = (GoodPushTwoTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: GoodPushTwoReuseId];
            }
            cell.model = newsArray[indexPath.row];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            return cell;
        }
        
        
    }
    
    return nil;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==4) {
        CardViewController *cardVC = [[CardViewController alloc]init];

        HPTask *model = taskArray[indexPath.row];
        cardVC.myTitle = model.tTitle;
        cardVC.myContent = model.tDescribe;
        cardVC.tid = model.tId;
        cardVC.createTime= model.createTime;
        cardVC.taskCout = taskArray.count;
        cardVC.tasks = taskArray;
        double cid =((HPChildren *)_hPViewModel.msg.me.children[0]).cId;
        cardVC.cid  = cid;
        
        
        
        cardVC.successBlock = ^(NSArray *successArray){
            NSInteger inter = -1;
            for (NSNumber *number in successArray) {
                if ([number integerValue] != inter) {
                    TodayAndPushTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[number integerValue] inSection:4]];
                    cell.img.image = [UIImage imageNamed:@"pass"];
                }
                inter = [number integerValue];
            }
            
        };

        [self presentViewController:cardVC animated:YES completion:nil];
    }
    else if (indexPath.section==0&&indexPath.row==0)
    {
        if (self.hPViewModel) {
            PeopleInfoViewController *searchVC = [[PeopleInfoViewController alloc]init];
            searchVC.childrenInfo = _hPViewModel.msg.me.children[0];
            searchVC.headUrlStr = _hPViewModel.msg.me.pHeadUrl;
            searchVC.nameLabel = _hPViewModel.msg.me.username;
            searchVC.phoneStr = _hPViewModel.msg.me.pMobile;
            WS
            searchVC.changImageBlcok = ^(void)
            {
                SS
                [strongSelf setPersonImage];
            };
            searchVC.changeInfoBlock = ^(NSString *phoneText,NSString *babyNickName,NSString *dateOfBirthText,NSString *sexText){
                MyTopTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                cell.BabyName.text = [NSString stringWithFormat:@"%@  %@",babyNickName,dateOfBirthText];

                if ([LocalFileManager getImageForKey:@"backGroundView"]) {
                    cell.bgImage.image = [LocalFileManager getImageForKey:@"backGroundView"];
                } else {
                    cell.bgImage.image = [UIImage imageNamed:@"first-figure"];
                }

                [myTableView.mj_header beginRefreshing];
            };

            [self.navigationController pushViewController:searchVC animated:YES];
        }
        
        
    }
    else if (indexPath.section==6)
    {
        NewsDetailViewController*VC = [[NewsDetailViewController alloc]init];
        HomePageNewsModel*model = newsArray[indexPath.row];
        VC.url= model.contentUrl;

        [self.navigationController pushViewController:VC animated:YES];
    }
    else if (indexPath.section==1)
    {
        NewsDetailViewController*VC = [[NewsDetailViewController alloc]init];
        TodayKnowledgeModel*model = todayKonwledgeArray[indexPath.row];
        VC.url= model.kContentUrl;

        [self.navigationController pushViewController:VC animated:YES];
    }
        
}

//每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 直接返回该indexPath对应cell的frame.size.height. (在cellForRowAtIndexPath方法中会重新更改)
    GoodPushTwoTableViewCell *cell = (GoodPushTwoTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// 计算指定文字的高度
-(CGFloat)sizeWithFont:(UIFont *)font maxW:(CGFloat) maxW withContent:(NSString *)testStr{
    
    NSDictionary *textAttrs = @{NSFontAttributeName : font};
    CGSize size = CGSizeMake(maxW, MAXFLOAT);
    return [testStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil].size.height;
    
}

// 获取cell最底部控件的最大Y值
-(CGFloat)getCellLastControlMaxY {
    // 获取cell中最底部的控件
    GoodPushTwoTableViewCell *tempCell = (GoodPushTwoTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"GoodPushTwoTableViewCell" owner:nil options:nil] lastObject];
    UILabel *lastLabel = tempCell.praseCount;
    return  lastLabel.frame.origin.y + lastLabel.bounds.size.height;
}
#pragma mark setPersonImage
- (void)setPersonImage
{
//    MyTopTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//    [cell.UserImgButton setBackgroundImage:[LocalFileManager getImageForKey:@"myUserImg"] forState:UIControlStateNormal];
//    cell.headImage.image = [LocalFileManager getImageForKey:@"myUserImg"];
//    cell.bgImage.image = [LocalFileManager getImageForKey:@"backGroundView"];
    
    
}

#pragma mark -------UICollectionView
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _hPViewModel.msg.knowledge.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"collectionviewID";
    HomeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell setModel:_hPViewModel.msg.knowledge[indexPath.row]];
    [cell filletWithcornerRadius:5];
    cell.img.image = [UIImage imageNamed:todayKnowledgeImg[indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((WIDTH-10)/3, 70);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 25, 5, 5);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewsDetailViewController*VC = [[NewsDetailViewController alloc]init];
    HomePageNewsModel*model = newsArray[indexPath.row];
    VC.url= model.contentUrl;

    [self.navigationController pushViewController:VC animated:YES];

}


#pragma mark goInToSearchPage
-(void)goInToSearchPage
{
    MySearchViewController *SearchVC = [[MySearchViewController alloc]init];
    SearchVC.hidesBottomBarWhenPushed = YES;
    SearchVC.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:SearchVC animated:YES];
    
   
}
#pragma mark goInToPersonalPage
-(void)goInToPersonalPage
{
    if (_hPViewModel) {
        PeopleInfoViewController *searchVC = [[PeopleInfoViewController alloc]init];
        //    SearchVC.hidesBottomBarWhenPushed = YES;
        //    SearchVC.tabBarController.tabBar.hidden = YES;
        searchVC.childrenInfo = _hPViewModel.msg.me.children[0];
        [self.navigationController pushViewController:searchVC animated:YES];
    }
}

#pragma mark --getNews
-(void)getNews
{
    
    NSString *pid = [[(NSDictionary *)GPGET(@"loginInfo") objectForKey:@"msg"] objectForKey:@"pId"];
 
    [GPAFNetworking3 post:GetNews parameters:@{@"pId":pid,@"page":@(currentPage)} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nullable responseObject) {
        TYH_LoginLoginModel *myModel = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (myModel.code!=1) {
            SHOW_ERROR
        }else{
            for (NSDictionary*myDict in responseObject[@"msg"]) {
                HomePageNewsModel *model = [[HomePageNewsModel alloc]init];
                [model yy_modelSetWithDictionary:myDict];
                [newsArray addObject:model];
                [myTableView.mj_footer endRefreshing];
                [myTableView reloadData];
            }
        }
        
        
    } failure:^(NSString * _Nonnull errorLD) {
        currentPage--;
       SHOW_NTERROR
    }];
}
#pragma mark --getTasks
-(void)getTasks
{
    NSArray *task = _hPViewModel.msg.task;
    taskArray  = [task mutableCopy];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getTodayKnowledge
{
    [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?pId=%@",GetTodayInfo,[[LoginManager shareLoginManager] getPid]] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (model.code!=1) {
            SHOW_ERROR
        }else{
            for (NSDictionary*myDict in responseObject[@"msg"][@"knowledge"])
            {
                TodayKnowledgeModel *model = [[TodayKnowledgeModel alloc]init];
                [model yy_modelSetWithDictionary:myDict];
                [todayKonwledgeArray addObject:model];
                [myTableView.mj_footer endRefreshing];
                [myTableView reloadData];
            }
        }
        
    } failure:^(NSString * _Nonnull errorLD) {
        SHOW_NTERROR
    }];
}

- (void)setAIV
{
    testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//    ScrollTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
//    testActivityIndicator.center = cell.center;
//    [cell addSubview:testActivityIndicator];
    testActivityIndicator.color = [UIColor redColor];
    [testActivityIndicator startAnimating];
    [testActivityIndicator setHidesWhenStopped:YES];
    [self.view addSubview:testActivityIndicator];
}


- (void)getPlayerData:(NSString *)playUrl
{
    if (!playUrl) {
        return;
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    __weak typeof(self) weakSelf = self;
    [session GET:playUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [cache setObject:responseObject forKey:@"playerData"];
        [weakSelf setPlayer:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
//    [session GET:playUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            [cache setObject:responseObject forKey:@"playerData"];
//            [weakSelf setPlayer:responseObject];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
}

- (void)setAudioPlayer
{
    [self setAIV];
    //    [self getPlayerData]
    cache = [[NSCache alloc] init];
    
}

- (UIImageView *)getImage
{
    if (voice) {
        return voice;
    }

    voice = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 9, 13.5)];

    NSMutableArray *imagesArray = [NSMutableArray array];
    for (int i = 0; i< 3; i++) {
        UIImage *Image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_play0%d(1)",i]];
        [imagesArray addObject:Image];
    }
    voice.image = [UIImage imageNamed:@"icon_play02(1)"];
    voice.animationImages = imagesArray;
    voice.animationRepeatCount = 0;
    voice.animationDuration = 1;

    return voice;
}

-(void)playVoice{
    ScrollTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    isAnimation = !isAnimation;
    cell.voiceButton.selected = !cell.voiceButton.selected;
    if (isAnimation)
        
    {
        for (UIImageView*imageView in cell.voiceButton.subviews) {
            [imageView startAnimating];
        }
        
        [player play];
    }
    else
    {
        for (UIImageView*imageView in cell.voiceButton.subviews) {
            [imageView stopAnimating];
        }
        
        [player pause];
    }
}

- (void)setPlayer:(NSData *)data
{
    ScrollTableViewCell *cell = [myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    [testActivityIndicator stopAnimating];
    cell.voiceButton.enabled = YES;
    player = [[AVAudioPlayer alloc] initWithData:data error:nil];
    player.volume = 1.0f;
    player.numberOfLoops = 0;
//    [player prepareToPlay];
    CGFloat fen = player.duration/60;
    NSInteger time = player.duration;
    CGFloat miao = time % 60;
    cell.timeLabel.text = [NSString stringWithFormat:@"%.f'%.f''",fen,miao];
    avStr = cell.timeLabel.text;
    success = YES;
//     [player play];
    for (UIActivityIndicatorView* activityIndicatorView in cell.voiceButton.subviews) {
        [activityIndicatorView stopAnimating];
    }
}



@end
